/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import com.bourre.events.BasicEvent;
import com.bourre.events.EventType;
import com.bourre.mvc.AbstractModel;

import fever.data.file.File;
import fever.log.FeverDebug;

import fvaswing.components.filechooser.events.FvFileChooserModelEvent;
import fvaswing.components.filechooser.factory.FvChooserStrategy;
import fvaswing.components.filechooser.mvc.FvFileChooserBuffer;

/**
 * <strong>FvFileChooserModel</strong> is the <strong>model</strong> 
 * part of the <strong>MVC Design pattern</strong> implemented in 
 * {@link fvaswing.components.FvFileChooser}.
 * 
 * <p>All datas are buffered with 
 * {@link fvaswing.components.filechooser.mvc.FvFileChooserBuffer} buffer 
 * system
 * 
 * @author Romain Ecarnot
 */
class fvaswing.components.filechooser.mvc.FvFileChooserModel extends AbstractModel 
{
	//-------------------------------------------------------------------------
	// Events definition
	//-------------------------------------------------------------------------
	
	/** Event name. */
	public static var onGetStrategyResultEVENT : EventType = new EventType( 'onGetStrategyResult' );
	
		
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private var _service : FvChooserStrategy;
	private var _currentPath : String;
	
		
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	public function FvFileChooserModel()
	{
		super();
	}
	
	/**
	 * 
	 */
	public function changeStrategy( strategy : FvChooserStrategy ) : Void
	{
		if( _service )
		{
			_service.removeEventListener( onGetStrategyResultEVENT , this );	
		}
		
		_service = strategy;
		_service.addEventListener( onGetStrategyResultEVENT, this, _onListResult );
	}
	
	/**
	 * Checks for a new listing.
	 * 
	 * <p>Uses the model cache if path is in.
	 */
	public function getList( path : String ) : Void
	{
		if( !_currentPath ) _currentPath = '/';
		var newPath : String = _currentPath + ( ( path ) ?  path + '/' : '' );
		
		_loadDirectory( newPath );
	}
	
	public function rescan( path : String ) : Void
	{
		_service.getContent( path );
	}
	
	/**
	 * Retreives list in model cache.
	 * 
	 * @param id Listing stored in model with {@code id} code
	 */
	public function retreiveList( id : String ) : Void
	{
		if( FvFileChooserBuffer.isBuffered( id ) )
		{
			var list : Array = FvFileChooserBuffer.getCacheList( id );
			_currentPath = id;
			
			notifyChanged( new FvFileChooserModelEvent( FvFileChooserModelEvent.UPDATE, id, list, FvFileChooserBuffer.getCachePaths() ) );
		}
	}
	
	/**
	 * Returns to parent directory
	 */
	public function getParent() : Void
	{
		var tmp : String = _rightTrim( _currentPath );
		tmp = tmp.substring( 0, tmp.lastIndexOf( '/' ) ) + '/';
		retreiveList( tmp );
	}
	
	/**
	 * Returns to home directory
	 */
	public function getHome() : Void
	{
		_loadDirectory( '/' );
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
		
	private function _onListResult( e : BasicEvent ) : Void
	{
		var result : Object = e.getTarget();
		
		FeverDebug.INFO( 'Receive raw content' );		FeverDebug.INFO( result );
		
		
		if( result.success )
		{
			var list : Array = new Array();
			var items : Array = result.list;
			
			_currentPath = result.path;
			
			for(var s in items )
			{
				var o : Object = items[s];
				var newFile : File = File.create( _currentPath + o.name );
				newFile.setSize( parseInt( o.size ) );
				newFile.setDirectory( o.type == 0 );
				newFile.setModifiedDate( new Date( o.time ) ); //TODO Date format in Chooser model
				
				list.push( newFile );
			}
			
			list.sortOn( [ 'type','name' ], Array.CASEINSENSITIVE );
			
			FvFileChooserBuffer.cache( _currentPath, list );
			
			notifyChanged( new FvFileChooserModelEvent( FvFileChooserModelEvent.UPDATE, _currentPath, list, FvFileChooserBuffer.getCachePaths() ) );
		}
		else
		{
			var event : FvFileChooserModelEvent = new FvFileChooserModelEvent( FvFileChooserModelEvent.ERROR );
			event.setSuccess( false );
			notifyChanged( e );	
		}
	}
	
	private function _loadDirectory( path : String ) : Void
	{
		if( FvFileChooserBuffer.isBuffered( path ) )
		{
			retreiveList( path );
		}
		else
		{
			_service.getContent( path );
		}
	}
	
	private function _rightTrim (source : String ) : String
	{
		var chars : String = '/';
		var i : Number = 0;
		var l : Number = source.length - 1;
		while ( i < l && chars.indexOf ( source.charAt (l) ) >= 0 ) l--;
		return ( l >= 0 ? source.substr ( i, l + 1 ) : source );
	}

}